package cn.fintecher.pangolin.service.dataimp.task;

import cn.fintecher.pangolin.common.enums.FollowType;
import cn.fintecher.pangolin.common.enums.PublicField;
import cn.fintecher.pangolin.common.enums.TaskBoxStatus;
import cn.fintecher.pangolin.common.enums.TaskBoxType;
import cn.fintecher.pangolin.common.model.TaskBoxModel;
import cn.fintecher.pangolin.common.model.UploadFile;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.BeanUtils;
import cn.fintecher.pangolin.common.utils.ExportDataToExcelUtil;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.common.utils.ZWStringUtils;
import cn.fintecher.pangolin.entity.elastic.CaseFollowupRecord;
import cn.fintecher.pangolin.entity.elastic.ExportTemplate;
import cn.fintecher.pangolin.entity.elastic.ExportTemplateItem;
import cn.fintecher.pangolin.service.dataimp.model.response.ExportFollowRecordModel;
import cn.fintecher.pangolin.service.dataimp.service.BaseService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 16:13 2019/10/19
 */

@Service("exportFollowRecordTask")
public class ExportFollowRecordTask {
    @Autowired
    private BaseService baseService;

    /**
     * 异步导出催记信息
     */
    @Async
    public void exportFollowRecord(List<CaseFollowupRecord> records, ExportTemplate exportTemplate, TaskBoxModel taskBoxModel, UserModel userModel) {
        if (records.isEmpty()) {
            String fileId = baseService.generateTxt(Collections.singletonList("没有催记数据导出"), Long.toString(new Date().getTime()));
            baseService.sendTaskBoxMessage(taskBoxModel, TaskBoxType.EXPORT, TaskBoxStatus.FAILURE, fileId, "催记信息导出", userModel, null, ZWDateUtil.getNowDateTime(), "催记导出");
        } else {
            try {
                List<ExportTemplateItem> items = exportTemplate.getItems();
                List<ExportFollowRecordModel> models = new ArrayList<>();
                for (CaseFollowupRecord record : records) {
                    ExportFollowRecordModel exportFollowRecordModel = new ExportFollowRecordModel();
                    BeanUtils.copyPropertiesIgnoreNull(record, exportFollowRecordModel);
                    processFollowType(record.getType(), exportFollowRecordModel);
                    models.add(exportFollowRecordModel);
                }
                List<List<String>> datas = parseRecord(models, exportTemplate);
                String path = FileUtils.getTempDirectoryPath().concat(File.separator).concat("催记导出" + System.currentTimeMillis()).concat(".xlsx");
                ExportDataToExcelUtil.exportToExcelForRecord(datas, items.stream().map(ExportTemplateItem::getTitleName).toArray(String[]::new), path);
                File file = new File(path);
                UploadFile uploadFile = baseService.uploadExcel(file);
                baseService.sendTaskBoxMessage(taskBoxModel, TaskBoxType.EXPORT, TaskBoxStatus.FINISHED, uploadFile.getId(), "催记导出", userModel, null, ZWDateUtil.getNowDateTime(), "催记导出");
            } catch (Exception e) {
                String fileId = baseService.generateTxt(Collections.singletonList("催记导出异常"), Long.toString(new Date().getTime()));
                baseService.sendTaskBoxMessage(taskBoxModel, TaskBoxType.EXPORT, TaskBoxStatus.FAILURE, fileId, "催记导出", userModel, null, ZWDateUtil.getNowDateTime(), "催记导出");
            }
        }
    }

    private List<List<String>> parseRecord(List<ExportFollowRecordModel> exportModels, ExportTemplate exportTemplate) {
        List<List<String>> dateList = new ArrayList<>();
        List<ExportTemplateItem> items = exportTemplate.getItems();
        Map<String, List<ExportFollowRecordModel>> map = exportModels.stream().collect(Collectors.groupingBy(ExportFollowRecordModel::getCaseId));
        for (Map.Entry<String, List<ExportFollowRecordModel>> entry : map.entrySet()) {
            List<ExportFollowRecordModel> list = entry.getValue();
            List<List<String>> strs = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                List<String> oneDate = new ArrayList<>();
                parseItems(items, list.get(i), oneDate, exportTemplate.getPublicField(), i);
                strs.add(oneDate);
            }
            dateList.addAll(strs);
        }
        return dateList;
    }

    private void parseItems(List<ExportTemplateItem> items, ExportFollowRecordModel exportModel, List<String> oneDate, PublicField publicField, int i) {
        if (publicField.equals(PublicField.FILL) || i == 0) { //填充
            for (ExportTemplateItem item : items) {
                String value = parseFieldsCase(exportModel, item.getAttribute());
                if (ZWStringUtils.isNotEmpty(item.getContent())) {
                    value = value + "|" + item.getContent();
                }
                oneDate.add(value);
            }
        } else if (publicField.equals(PublicField.NO_FILL) && i > 0) { //不填充
            exportModel.setCaseId(null);
            exportModel.setCertificateNo(null);
            exportModel.setCaseNumber(null);

            for (ExportTemplateItem item : items) {
                String value = parseFieldsCase(exportModel, item.getAttribute());
                if (ZWStringUtils.isNotEmpty(item.getContent())) {
                    value = value + "|" + item.getContent();
                }
                oneDate.add(value);
            }
        }
    }

    private String parseFieldsCase(ExportFollowRecordModel exportModel, String attribute) {
        Field field;
        try {
            if (Objects.nonNull(attribute)) {
                field = exportModel.getClass().getDeclaredField(attribute);
                field.setAccessible(true);
                if (Objects.nonNull(field.get(exportModel))) {
                    if (Objects.equals(field.getType().getName(), "java.util.Date")) {
                        return ZWDateUtil.fomratterDate((Date) field.get(exportModel), "yyy-MM-dd");
                    } else {
                        return field.get(exportModel).toString();
                    }
                } else {
                    return "";
                }
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 处理跟进方式
     */
    private void processFollowType(FollowType type, ExportFollowRecordModel exportFollowRecordModel) {
        if (Objects.nonNull(type)) {
            switch (type.name()) {
                case "TEL":
                    exportFollowRecordModel.setType("电话");
                    break;
                case "ADDR":
                    exportFollowRecordModel.setType("地址");
                    break;
                case "ASSIST_TEL":
                    exportFollowRecordModel.setType("协催电话");
                    break;
                case "ASSIST_ADDR":
                    exportFollowRecordModel.setType("外访地址");
                    break;
                case "FIND":
                    exportFollowRecordModel.setType("查找");
                    break;
            }
        }
    }
}
